package com.zsd.android.webrtcdemo;

import android.app.Activity;

import com.zsd.android.webrtcdemo.connection.PeerConnectionManager;
import com.zsd.android.webrtcdemo.interfaces.IViewCallback;
import com.zsd.android.webrtcdemo.socket.JavaWebSocket;

import org.webrtc.EglBase;

public class WebRTCManager {

    private static volatile WebRTCManager instance;
    private JavaWebSocket webSocket;
    private PeerConnectionManager peerConnectionManager;
    private String roomId;

    private WebRTCManager() {}

    public static WebRTCManager getInstance() {
        WebRTCManager manager = instance;
        if (manager == null) {
            synchronized (WebRTCManager.class) {
                if (manager == null) {
                    manager = new WebRTCManager();
                    instance = manager;
                }
            }
        }
        return manager;
    }

    public void connect(Activity activity, String roomId) {
        this.roomId = roomId;
        peerConnectionManager = PeerConnectionManager.getInstance();
        webSocket = new JavaWebSocket(activity);
        webSocket.connect("");
    }

    public void joinRoom(Activity activity, EglBase rootEglBase) {
        peerConnectionManager.initContext(activity, rootEglBase);
        webSocket.joinRoom(roomId);
    }

    public void toggleMic(boolean enableMic) {
        if (peerConnectionManager != null) {
            peerConnectionManager.toggleSpeaker(enableMic);
        }
    }

    public void toggleLager(boolean enableSpeaker) {
        if (peerConnectionManager != null) {
            peerConnectionManager.toggleLager(enableSpeaker);
        }
    }

    public void toggleOpenCamera(boolean enableCamera) {
        if (peerConnectionManager != null) {
            peerConnectionManager.toggleOpenCamera(enableCamera);
        }
    }

    public void toggleCamera() {
        if (peerConnectionManager != null) {
            peerConnectionManager.toggleCamera();
        }
    }

    public void handUp() {
        if (peerConnectionManager != null) {
            peerConnectionManager.handUp();
        }
    }

    public void exitRoom() {
        if (peerConnectionManager != null) {
            webSocket = null;
            peerConnectionManager.exitRoom();
        }
    }

    public void setCallback(IViewCallback viewCallback) {
        peerConnectionManager.setViewCallback(viewCallback);
    }
}
